//
//  iOSAppDelegate.m
//  GSEngine
//
//  Created by Гукун Александр on 1/23/14.
//  Copyright (c) 2014 SNK. All rights reserved.
//

#import "iOSAppDelegate.h"
#import "iOSViewController.h"
#import "iOSWindow.h"
#include <GSEngine/Main/GSApplication.h>
#include <GSEngine/Objects/EntityManager.h>
#include <GSEngine/Input/InputManager.h>

@class iOSGLESView;
@class iOSViewController;

using namespace GSEngine;

@implementation iOSAppDelegate

static iOSAppDelegate* iOSAppDelegateInstance = nil;



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    NSLog(@"DidFinishLaunching");
    iOSAppDelegateInstance = self;
    mainWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [mainWindow makeKeyAndVisible];
    
    mainController = [[iOSViewController alloc] init];
    [mainWindow setRootViewController:mainController];
    
    iOSWindow *gsWindow = (iOSWindow*)(GSEngine::GSApplication::getInstance()->getPlatform()->getWindow());
    mainView = gsWindow->getRenderView();
    [mainController setView:mainView];
//    [mainView setDelegate:self];
    [mainWindow addSubview:mainView];
    
    [mainView startAnimation];
    
    return YES;
}

- (void)render{
    glClear(GL_COLOR_BUFFER_BIT);
    // entity manager render
    GSEngine::EntityManager::getInstance()->render();
}

+ (iOSAppDelegate*)getInstance{
    return iOSAppDelegateInstance;
}

- (CGPoint)screenPointFromTouch:(UITouch*)touch
{
	return [touch locationInView:mainView];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	for (UITouch *touch in touches)
	{
		CGPoint point = [self screenPointFromTouch:touch];
		int touchId = (int)(touch);
        InputManager::getInstance()->beginTouch(vec2f(point.x,point.y), touch.tapCount, touchId);
	}
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	for (UITouch *touch in touches)
	{
		CGPoint point = [self screenPointFromTouch:touch];
		int touchId = (int)(touch);
        InputManager::getInstance()->moveTouch(vec2f(point.x,point.y), touch.tapCount, touchId);	}
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	for (UITouch *touch in touches)
	{
		CGPoint point = [self screenPointFromTouch:touch];
		int touchId = (int)(touch);
        InputManager::getInstance()->endTouch(vec2f(point.x,point.y), touch.tapCount, touchId);	}
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
	for (UITouch *touch in touches)
	{
		CGPoint point = [self screenPointFromTouch:touch];
		int touchId = (int)(touch);
        InputManager::getInstance()->cancelTouch(vec2f(point.x,point.y), touch.tapCount, touchId);	}
}


@end
